package c.x.jy.common.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

 
 

public class CookieUtil {

	
	
	/**
	 * 得到Cookie的值,
	 *
	 * @param request 请求
	 * @param cookieName cookie的名字
	 * @param isDecoder 是否需要转码
	 * @return
	 */
	public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {
	    Cookie[] cookieList = request.getCookies();
	    if (cookieList == null || cookieName == null) {
	        return null;
	    }
	    String retValue = null;
	    try {
	        for (int i = 0; i < cookieList.length; i++) {
	            if (cookieList[i].getName().equals(cookieName)) {
	                if (isDecoder) {
	                    retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8");
	                } else {
	                    retValue = cookieList[i].getValue();
	                }
	                break;
	            }
	        }
	    } catch (UnsupportedEncodingException e) {
	        e.printStackTrace();
	    }
	    return retValue;
	}
	/**
	 * 设置Cookie的值，并使其在指定时间内生效
	 *
	 * @param cookieMaxage cookie生效的最大秒数
	 */
	public static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,
	                                      String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {
	    try {
	        if (cookieValue == null) {
	            cookieValue = "";
	        } else if (isEncode) {
	            cookieValue = URLEncoder.encode(cookieValue, "utf-8");
	        }
	        Cookie cookie = new Cookie(cookieName, cookieValue);
	        if (cookieMaxage > 0)
	            cookie.setMaxAge(cookieMaxage);
	        if (null != request) {// 设置域名的cookie
	            String domainName = getDomainName(request);
	      
	            if (!"localhost".equals(domainName)) {
	             //   cookie.setDomain(domainName);
	            }
	        }
	        cookie.setPath("/");
	        response.addCookie(cookie);
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	}
	/**
	 * 得到cookie的域名
	 */
	private static final String getDomainName(HttpServletRequest request) {
		StringBuffer url = request.getRequestURL();  
		String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()) .toString();  
	    return tempContextUrl.substring(tempContextUrl.indexOf(":")+3);
	}
}
